// File: src/game/xp/XPSystem.cpp
#include "XPSystem.h"
#include <fstream>
#include <sstream>

void XPSystem::saveToFile(const std::string& username, 
    const std::vector<Territory>& territories) {
    std::ofstream file(username + "_gameData_" +".tmdb");
    if (file.is_open()) {
        // 写入表头（注释行）
        file << "# 文件格式说明:\n";
        file << "# 第一行: currentXP currentLevel\n";
        file << "# 后续行: 领土类型(0=城堡,1=森林,2=山脉,3=河流) 领土大小\n";
        file << "# --------------------------\n";
        
        // 写入实际数据（XP和等级）
        file << currentXP << " " << currentLevel << "\n";
        
        // 写入领土数据
        for (const auto& territory : territories) {
            file << static_cast<int>(territory.getType()) << " " 
                 << territory.getSize() << "\n";
        }
    }
}

void XPSystem::loadFromFile(const std::string& username, 
    std::vector<Territory>& territories) {
    std::ifstream file(username + "_gameData_" +".tmdb");
    if (file.is_open()) {
        std::string line;
        
        // 跳过注释行（以 # 开头）
        while (std::getline(file, line)) {
            if (line.empty() || line[0] == '#') continue;
            
            // 读取第一行数据（XP和等级）
            int xp, level;
            std::istringstream iss(line);
            iss >> xp >> level;
            currentXP = xp;
            currentLevel = level;
            break;
        }
        
        // 读取领土数据
        int type, size;
        while (file >> type >> size) {
            territories.emplace_back(static_cast<TerritoryType>(type));
            territories.back().setSize(size);
        }
        file.close();
    } else {
        // 文件不存在时初始化默认值
        currentXP = 0;
        currentLevel = 1;
    }
}